package com.shujia.flink.core

import org.apache.flink.api.common.eventtime.WatermarkStrategy
import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.configuration.Configuration
import org.apache.flink.connector.kafka.source.KafkaSource
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer
import org.apache.flink.streaming.api.functions.sink.{RichSinkFunction, SinkFunction}
import org.apache.flink.streaming.api.scala._

import java.sql.{Connection, DriverManager, PreparedStatement}

object Demo4SubmitOnKafka {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    //1、从kafka中读取数据
    val source: KafkaSource[String] = KafkaSource
      .builder[String]
      .setBootstrapServers("master:9092,node1:9092,node2:9092") //kafka集群列表
      .setTopics("student") //topic
      .setGroupId("Demo4SubmitOnKafka") //消费者组
      .setStartingOffsets(OffsetsInitializer.earliest()) //读取数据的位置
      .setValueOnlyDeserializer(new SimpleStringSchema()) //反序列化类
      .build

    //构建DataStream
    val kafkaSource: DataStream[String] = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source")

    //统计班级人数
    val kvDS: DataStream[(String, Int)] = kafkaSource.map(line => {
      val clazz: String = line.split(',').last
      (clazz, 1)
    })
    val clazzNumDS: DataStream[(String, Int)] = kvDS.keyBy(_._1).sum(1)

    /**
     * 将统计好的结果保存到数据库中
     *
     */
    clazzNumDS.addSink(new RichSinkFunction[(String, Int)] {

      var con: Connection = _
      var stat: PreparedStatement = _

      override def invoke(value: (String, Int), context: SinkFunction.Context): Unit = {
        stat.setString(1, value._1)
        stat.setInt(2, value._2)
        stat.execute()
      }

      override def open(parameters: Configuration): Unit = {
        //在open中创建数据库链接
        Class.forName("com.mysql.jdbc.Driver")
        //建立链接
        con = DriverManager.getConnection("jdbc:mysql://master:3306/bigdata", "root", "123456")
        stat = con.prepareStatement("replace into clazz_num(clazz,num) values(?,?)")
      }

      override def close(): Unit = {
        //关闭链接
        stat.close()
        con.close()
      }
    })


    env.execute()

    /**
     * 提交任务
     * flink run -t yarn-per-job -c com.shujia.flink.core.Demo4SubmitOnKafka  flink-1.0-SNAPSHOT.jar
     */
  }

}
